<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline">

        </a-form>
        <Toolbar :items="['查询']" @select="selectHandle" @add="addHandle" @del="deleteHandle">
        </Toolbar>
    </div>
    <div class="cssTable">
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :style="{ height: pageData.rHeight - 200 + 'px' }" :suppressDragLeaveHidesColumns="true"
                rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                :rowData="pageData.tableList" :columnDefs="tableColumns" :localeText="localeText1"
                @columnResized="onColumnResized" @columnMoved="onColumnMoved" @columnVisible="onColumnVisible">
            </AgGridVuesCopys>
        </a-spin>
    </div>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
        @change="PageSize" @page-size-change="change1" style="justify-content: center;margin-top:12px;"
        :page-size="size" :current="page" />
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
        :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="horizontal" :model="dataForm">
                <a-form-item label-col-flex="80px" label="数值" field="conditionValue"
                    :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '数值必填' }]">
                    <a-input-number class="bacClass" v-model="dataForm.conditionValue" :min="0" :precision="0" />
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    showAdd: false,
    sideTitle: '',
    rHeight: 0,
    tableList: [],
    pageLoading: false,
    inspectName: '',
    unitList: [],
})

const dataForm: any = reactive({
    conditionValue: '',
})

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
}
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}

const tableColumns: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50
    },
    { headerName: "序号", field: "id", width: 150, },
    {
        headerName: "缺陷类型", field: "standardTypeId", width: 150,
        cellRenderer: {
            template: `<span>{{val.standardTypeId === 1 ? '入疵' : '降等'}}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value == '1' ? '入疵' : '降等'
            },
        }
    },
    {
        headerName: "定义", field: "conditionType", width: 150,
        cellRenderer: {
            template: `<span>{{val.conditionType === 1 ? '重量' : '数量'}}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value == '1' ? '重量' : '数量'
            },
        }
    },
    { headerName: "数值", field: "standardCount", width: 150, },
    { headerName: "单位", field: "standardUnit", width: 150, },
    {
        headerName: "条件", field: "conditionOperate", width: 150,
        cellRenderer: {
            template: `<span>{{val.conditionOperate === 1 ? '>=' : '<='}}</span>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value == '1' ? '>=' : '<='
            },
        }
    },
    { headerName: "数值", field: "conditionValue", width: 150, },
    { headerName: "单位", field: "unit", width: 150, },
    { headerName: "创建时间", field: "createTime", width: 150, },
    {
        headerName: "状态", field: "enabled", pinned: 'right', width: 150,
        cellRenderer: {
            template: `<el-tag type="success" v-if="val.enabled == 1">启用</el-tag>
            <el-tag type='info' v-else>停用</el-tag>`,
            setup(props: any) {
                let val = ref(props.params.data)
                return {
                    val,
                }
            },
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value == '1' ? '启用' : '停用'
            },
        }
    },
    {
        headerName: "操作",
        field: "action",
        width: 150,
        pinned: 'right',
        cellRenderer: {
            template: `<el-button style="color:#165dff;" link @click="c">修改</el-button>`,
            setup(props: any) {
                const c = () => {
                    editHanler(props.params.data)
                }
                return {
                    c,
                }
            },
        },
    }
]

//分页
const total = ref(0);
const page = ref(1);
const size = ref(10);
function PageSize(val: any) {
    page.value = val
    doRefresh();
}
function change1(val: any) {
    size.value = val
    doRefresh();
}

//查询
function doRefresh() {
    pageData.pageLoading = true
    updateGridState01()
    post({
        url: "/qms/qualityStandard/listQualityStandards",
        data: {
            current: page.value,
            size: size.value,
        }
    })
        .then(({ data, code }: any) => {
            if (code === 200) {
                pageData.tableList = data
                gridOption.value.setRowData(data)
                total.value = data.total;
            }
        })
        .catch(console.log).finally(() => {
            pageData.pageLoading = false
        })
}

const selectHandle = () => {
    page.value = 1
    doRefresh()
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    doRefresh()
})

//新增
const addHandle = () => {
    if (dataForm.id) {
        delete dataForm.id
    }
    for (let item in dataForm) {
        dataForm[item] = ''
    }
    dataForm.unit = 'KG'
    pageData.showAdd = true
    pageData.sideTitle = '新增事故条件设置'
}

//修改
const editHanler = (record: any) => {
    for (let item in dataForm) {
        dataForm[item] = record[item]
    }
    dataForm.id = record.id
    pageData.showAdd = true
    pageData.sideTitle = '修改事故条件设置'
}

const formRef = ref()
const sideOk = () => {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            post({
                url: '/qms/qualityStandard/updateQualityStandard',
                data: dataForm
            }).then(({ code, message }) => {
                if (code == 200) {
                    Message.success('成功')
                    pageData.showAdd = false
                    doRefresh()
                } else {
                    Message.error(message)
                }
            })
        }
    })
}

//删除
const deleteHandle = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请勾选数据')
        return false
    }
    Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk: () => {
            post({
                url: '/qms/inspectionEmployee/delInspectionPositions',
                data: gridOption.value.getSelectedRows().map((res: any) => res.id),
            }).then((res: any) => {
                if (res.code == 200) {
                    Message.success('删除成功')
                    doRefresh()
                } else Message.error(res.message)
            })
        },
    })
}

//获取单位下拉框
function getUnitList() {
    post({
        url: 'dict/dictTypeDetail/getListByCodeType?codeType=17',
    }).then((res: any) => {
        if (res.code == 200) {
            pageData.unitList = res.data
        }
    })
}

const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('SOPposts-1', gridOption, colState, tableColumns)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
const onColumnVisible = () => {
    saveGridState01()
}
</script>

<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>